<template>
  <div class="starrocks-cps-form">
    <el-form label-width="140px" :model="localValue">
      <section class="form-section">
        <div class="section-title">
          <el-icon class="data-source-icon"><Histogram /></el-icon>
          <span>数据源配置</span>
        </div>
        <el-form-item label="StarRocks 数据源" required>
          <DataSourceSelector
            v-model="dataSourceIdForSelector"
            service-type="starrocks"
            placeholder="请选择数据源"
          />
        </el-form-item>
      </section>

      <section class="form-section">
        <div class="section-title">
          <el-icon class="platform-icon"><List /></el-icon>
          <span>平台选择</span>
        </div>
        
        <!-- 平台选择容器 -->
        <div class="platform-selection-container">
          <!-- 平台多选框组 -->
          <el-checkbox-group 
            v-model="localValue.platform_filter.selected_platforms" 
            @change="emitParams"
            class="platform-checkbox-group"
          >
            <div class="platform-row">
              <el-checkbox 
                v-for="platform in platformOptions" 
                :key="platform.value"
                :label="platform.value"
                class="platform-checkbox"
              >
                <div class="platform-item">
                  <el-icon class="platform-icon">
                    <component :is="platform.icon" />
                  </el-icon>
                  <span class="platform-name">{{ platform.label }}</span>
                  <span class="platform-code">({{ platform.value }})</span>
                </div>
              </el-checkbox>
            </div>
          </el-checkbox-group>
          
          <!-- 快捷操作按钮 -->
          <div class="quick-actions">
            <el-button size="small" @click="selectAllPlatforms">
              <el-icon><Select /></el-icon>
              全选
            </el-button>
            <el-button size="small" @click="clearAllPlatforms">
              <el-icon><Close /></el-icon>
              清空
            </el-button>
            <el-button size="small" type="primary" @click="selectCommonPlatforms">
              <el-icon><Star /></el-icon>
              常用平台
            </el-button>
          </div>
        </div>
        
        <!-- 选中平台预览 -->
        <div v-if="localValue.platform_filter.selected_platforms.length > 0" class="selected-preview">
          <div class="preview-header">
            <el-icon><View /></el-icon>
            <span>已选择平台 ({{ localValue.platform_filter.selected_platforms.length }})</span>
          </div>
          <div class="preview-content">
            <el-tag 
              v-for="platform in localValue.platform_filter.selected_platforms" 
              :key="platform"
              type="info"
              size="small"
              class="platform-tag"
              closable
              @close="removePlatform(platform)"
            >
              {{ getPlatformName(platform) }}
            </el-tag>
          </div>
        </div>
        
        <!-- 平台统计信息 -->
        <div class="platform-stats">
          <el-alert
            v-if="localValue.platform_filter.selected_platforms.length === 0"
            title="请至少选择一个平台"
            type="warning"
            :closable="false"
            show-icon
          />
          <el-alert
            v-else
            :title="`已选择 ${localValue.platform_filter.selected_platforms.length} 个平台`"
            type="success"
            :closable="false"
            show-icon
          />
        </div>
      </section>

      <section class="form-section">
        <div class="section-title">
          <el-icon class="time-comparison-icon"><Clock /></el-icon>
          <span>时间对比配置</span>
        </div>
        
        <div class="time-comparison-container">
          <!-- 对比类型选择 -->
          <div class="comparison-type-section">
            <div class="item-header">
              <el-icon><Calendar /></el-icon>
              <span>对比类型</span>
              <el-tooltip content="选择时间对比模式：天（昨天vs今天）、昨天和前天（前天vs昨天）、月（上月vs本月）、年（去年vs今年）或自定义" placement="top">
                <el-icon class="help-icon"><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
            
            <el-radio-group 
              v-model="localValue.time_comparison.comparison_type" 
              @change="handleComparisonTypeChange"
              class="comparison-type-group"
            >
              <el-radio label="day" class="comparison-radio">
                <div class="radio-item">
                  <el-icon><Calendar /></el-icon>
                  <span>天（昨天 vs 今天）</span>
                </div>
              </el-radio>
              <el-radio label="yesterday" class="comparison-radio">
                <div class="radio-item">
                  <el-icon><Calendar /></el-icon>
                  <span>昨天和前天（前天 vs 昨天）</span>
                </div>
              </el-radio>
              <el-radio label="month" class="comparison-radio">
                <div class="radio-item">
                  <el-icon><Calendar /></el-icon>
                  <span>月（上月 vs 本月）</span>
                </div>
              </el-radio>
              <el-radio label="year" class="comparison-radio">
                <div class="radio-item">
                  <el-icon><Calendar /></el-icon>
                  <span>年（去年 vs 今年）</span>
                </div>
              </el-radio>
              <el-radio label="custom" class="comparison-radio">
                <div class="radio-item">
                  <el-icon><Calendar /></el-icon>
                  <span>自定义</span>
                </div>
              </el-radio>
            </el-radio-group>
          </div>

          <!-- 自定义日期选择 -->
          <div v-if="localValue.time_comparison.comparison_type === 'custom'" class="custom-date-section">
            <div class="item-header">
              <el-icon><Calendar /></el-icon>
              <span>自定义日期</span>
            </div>
            <div class="date-picker-row">
              <el-form-item 
                label="基准日期" 
                style="margin-right: 20px;"
                :class="{ 'is-error': baseDateError }"
                class="date-input-item"
              >
                <el-input
                  v-model="baseDateValue"
                  placeholder="例如：2025-01-15 或 2025-01 或 2025"
                  :class="{ 'is-error': baseDateError }"
                  @blur="handleBaseDateBlur"
                  @input="handleBaseDateInput"
                  clearable
                >
                  <template #append>
                    <el-button @click="showDatePicker('base')">
                      <el-icon><Calendar /></el-icon>
                    </el-button>
                  </template>
                </el-input>
                <div class="error-message-wrapper">
                  <transition name="error-fade">
                    <div v-if="baseDateError" class="error-message">
                      <el-icon class="error-icon"><WarningFilled /></el-icon>
                      <span>{{ baseDateError }}</span>
                    </div>
                  </transition>
                </div>
              </el-form-item>
              <el-form-item 
                label="对比日期"
                :class="{ 'is-error': compareDateError }"
                class="date-input-item"
              >
                <el-input
                  v-model="compareDateValue"
                  placeholder="例如：2025-01-15 或 2025-01 或 2025"
                  :class="{ 'is-error': compareDateError }"
                  @blur="handleCompareDateBlur"
                  @input="handleCompareDateInput"
                  clearable
                >
                  <template #append>
                    <el-button @click="showDatePicker('compare')">
                      <el-icon><Calendar /></el-icon>
                    </el-button>
                  </template>
                </el-input>
                <div class="error-message-wrapper">
                  <transition name="error-fade">
                    <div v-if="compareDateError" class="error-message">
                      <el-icon class="error-icon"><WarningFilled /></el-icon>
                      <span>{{ compareDateError }}</span>
                    </div>
                  </transition>
                </div>
              </el-form-item>
            </div>
          </div>

          <!-- 时间预览 -->
          <div class="time-preview">
            <div class="preview-header">
              <el-icon><View /></el-icon>
              <span>时间对比预览</span>
            </div>
            <div class="preview-content">
              <div class="preview-item">
                <span class="label">基准日期:</span>
                <el-tag type="info" size="small">{{ getBaseDateText() }}</el-tag>
              </div>
              <div class="preview-item">
                <span class="label">对比日期:</span>
                <el-tag type="primary" size="small">{{ getCompareDateText() }}</el-tag>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section class="form-section">
        <div class="section-title">
          <el-icon class="display-fields-icon"><Filter /></el-icon>
          <span>显示字段</span>
        </div>
        <el-checkbox-group
          v-model="localValue.display_fields"
          class="display-fields"
          @change="emitParams"
        >
          <el-checkbox
            v-for="field in displayFieldOptions"
            :key="field.value"
            :label="field.value"
          >
            {{ field.label }}
          </el-checkbox>
        </el-checkbox-group>
      </section>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { reactive, watch, defineExpose, computed, ref, onMounted } from 'vue'
import { 
  Filter, Histogram, List, Select, Close, Star, 
  QuestionFilled, View, ShoppingBag, Shop, ShoppingCart, VideoPlay, 
  Box, Goods, MoreFilled, Clock, Calendar, WarningFilled
} from '@element-plus/icons-vue'
import DataSourceSelector from '../../shared/DataSourceSelector.vue'
import type { TemplateMeta } from '../registry'
import api from '@/utils/api'

interface CpsBaseStatisticsParams {
  data_source_config: {
    data_source_id: number | null
  }
  platform_filter: {
    selected_platforms: string[]
  }
  time_comparison: {
    comparison_type: 'day' | 'yesterday' | 'month' | 'year' | 'custom'
    base_date?: string | null  // YYYY-MM-DD, YYYY-MM, or YYYY
    compare_date?: string | null  // YYYY-MM-DD, YYYY-MM, or YYYY
  }
  display_fields: string[]
}

const props = defineProps<{
  modelValue: CpsBaseStatisticsParams | null
  templateMeta?: TemplateMeta | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: CpsBaseStatisticsParams): void
  (e: 'validate', payload: { valid: boolean; errors: string[] }): void
}>()

const defaultValue = (): CpsBaseStatisticsParams => ({
  data_source_config: {
    data_source_id: null
  },
  platform_filter: {
    selected_platforms: ['dy', 'tb', 'jd', 'pdd']
  },
  time_comparison: {
    comparison_type: 'day',
    base_date: null,
    compare_date: null
  },
  display_fields: [
    'data_comment',
    'platform',
    'base_date_count',
    'compare_date_count',
    'increment',
    'growth_rate',
    'trend'
  ]
})

const localValue = reactive<CpsBaseStatisticsParams>({
  ...defaultValue(),
  ...(props.modelValue || {})
})

// 用于 DataSourceSelector 的计算属性
const dataSourceIdForSelector = computed({
  get: () => localValue.data_source_config.data_source_id ?? undefined,
  set: (value: number | undefined) => {
    localValue.data_source_config.data_source_id = value ?? null
    emitParams()
  }
})

// 默认平台选项（作为后备）
const defaultPlatformOptions = [
  { value: 'tb', label: '淘宝联盟 (tb)', icon: 'ShoppingBag' },
  { value: 'tbc', label: '淘宝招商团长 (tbc)', icon: 'Shop' },
  { value: 'tbb', label: '淘宝商单广场 (tbb)', icon: 'ShoppingCart' },
  { value: 'dy', label: '抖音好单库 (dy)', icon: 'VideoPlay' },
  { value: 'dyc', label: '抖音团长 (dyc)', icon: 'VideoPlay' },
  { value: 'jd', label: '京东联盟 (jd)', icon: 'Box' },
  { value: 'pdd', label: '多多进宝 (pdd)', icon: 'Goods' },
  { value: 'vph', label: '唯品会开放平台 (vph)', icon: 'MoreFilled' }
]

// 平台选项（从 API 获取或使用默认值）
const platformOptions = ref<Array<{ value: string; label: string; icon: string }>>(defaultPlatformOptions)

// 图标映射
const iconMap: Record<string, string> = {
  'tb': 'ShoppingBag',
  'tbc': 'Shop',
  'tbb': 'ShoppingCart',
  'dy': 'VideoPlay',
  'dyc': 'VideoPlay',
  'jd': 'Box',
  'pdd': 'Goods',
  'vph': 'MoreFilled'
}

// 从 API 获取平台列表
const fetchPlatformList = async () => {
  try {
    const templateCode = 'cps_base_statistics_report'
    const response = await api.get(`/reports/templates/${templateCode}/platforms`)
    
    if (response.data?.success && response.data?.data) {
      const platforms = response.data.data
      platformOptions.value = platforms.map((p: { value: string; label: string }) => ({
        value: p.value,
        label: `${p.label} (${p.value})`,
        icon: iconMap[p.value] || 'MoreFilled'
      }))
    }
  } catch (error: any) {
    console.warn('[StarrocksCpsBaseStatisticsForm] 获取平台列表失败，使用默认列表:', error)
    platformOptions.value = defaultPlatformOptions
  }
}

onMounted(() => {
  fetchPlatformList()
})

// 常用平台配置
const commonPlatforms = ['dy', 'tb', 'jd', 'pdd']

const displayFieldOptions = [
  { value: 'data_comment', label: '数据说明' },
  { value: 'platform', label: '平台' },
  { value: 'base_date_count', label: '基准日期总量' },
  { value: 'compare_date_count', label: '对比日期总量' },
  { value: 'increment', label: '增量' },
  { value: 'growth_rate', label: '环比增长率' },
  { value: 'trend', label: '变化趋势' }
]

const displayFieldOrder = displayFieldOptions.map((opt) => opt.value)

const sortDisplayFields = () => {
  if (!Array.isArray(localValue.display_fields)) {
    localValue.display_fields = []
  }
  const uniqueSelected = Array.from(new Set(localValue.display_fields))
  const sorted: string[] = []

  displayFieldOrder.forEach((field) => {
    if (uniqueSelected.includes(field)) {
      sorted.push(field)
    }
  })

  uniqueSelected.forEach((field) => {
    if (!sorted.includes(field)) {
      sorted.push(field)
    }
  })

  const changed =
    sorted.length !== localValue.display_fields.length ||
    sorted.some((field, idx) => field !== localValue.display_fields[idx])

  if (changed) {
    localValue.display_fields = sorted
  }
}

sortDisplayFields()

const emitParams = () => {
  sortDisplayFields()
  const payload = JSON.parse(JSON.stringify(localValue))
  emit('update:modelValue', payload)
}

// 平台操作方法
const getPlatformName = (platform: string) => {
  const option = platformOptions.value.find(opt => opt.value === platform)
  return option ? option.label : platform
}

const selectAllPlatforms = () => {
  localValue.platform_filter.selected_platforms = platformOptions.value.map(opt => opt.value)
  emitParams()
}

const clearAllPlatforms = () => {
  localValue.platform_filter.selected_platforms = []
  emitParams()
}

const selectCommonPlatforms = () => {
  localValue.platform_filter.selected_platforms = [...commonPlatforms]
  emitParams()
}

const removePlatform = (platform: string) => {
  const index = localValue.platform_filter.selected_platforms.indexOf(platform)
  if (index > -1) {
    localValue.platform_filter.selected_platforms.splice(index, 1)
    emitParams()
  }
}

// 时间对比相关方法
const baseDateValue = ref<string | null>(null)
const compareDateValue = ref<string | null>(null)
const baseDateError = ref<string>('')
const compareDateError = ref<string>('')

const handleComparisonTypeChange = () => {
  // 根据对比类型自动计算日期（非自定义模式）
  if (localValue.time_comparison.comparison_type !== 'custom') {
    const now = new Date()
    let baseDate: Date
    let compareDate: Date = new Date(now)

    if (localValue.time_comparison.comparison_type === 'day') {
      // 昨天 vs 今天
      baseDate = new Date(now)
      baseDate.setDate(baseDate.getDate() - 1)
    } else if (localValue.time_comparison.comparison_type === 'yesterday') {
      // 前天 vs 昨天
      baseDate = new Date(now)
      baseDate.setDate(baseDate.getDate() - 2)
      compareDate = new Date(now)
      compareDate.setDate(compareDate.getDate() - 1)
    } else if (localValue.time_comparison.comparison_type === 'month') {
      // 上月 vs 本月（月份格式）
      // 计算上个月：当前月份的第一天减去1天就是上个月的最后一天
      const firstDayOfThisMonth = new Date(now.getFullYear(), now.getMonth(), 1)
      baseDate = new Date(firstDayOfThisMonth.getTime() - 24 * 60 * 60 * 1000) // 上个月最后一天（用于格式化月份）
      compareDate = now // 本月（用于格式化月份）
    } else if (localValue.time_comparison.comparison_type === 'year') {
      // 去年1月1日 vs 今年1月1日
      baseDate = new Date(now.getFullYear() - 1, 0, 1)
      compareDate = new Date(now.getFullYear(), 0, 1)
    } else {
      return
    }

    // 根据对比类型格式化日期
    let baseDateStr: string
    let compareDateStr: string
    
    if (localValue.time_comparison.comparison_type === 'month') {
      // 月份格式：YYYY-MM
      const formatMonth = (date: Date): string => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        return `${year}-${month}`
      }
      baseDateStr = formatMonth(baseDate)
      compareDateStr = formatMonth(compareDate)
    } else if (localValue.time_comparison.comparison_type === 'year') {
      // 年份格式：YYYY
      baseDateStr = String(baseDate.getFullYear())
      compareDateStr = String(compareDate.getFullYear())
    } else {
      // 日期格式：YYYY-MM-DD
      const formatDate = (date: Date): string => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
      }
      baseDateStr = formatDate(baseDate)
      compareDateStr = formatDate(compareDate)
    }

    localValue.time_comparison.base_date = baseDateStr
    localValue.time_comparison.compare_date = compareDateStr
    baseDateValue.value = localValue.time_comparison.base_date
    compareDateValue.value = localValue.time_comparison.compare_date
  }
  emitParams()
}

// 日期格式验证函数
const validateDateFormat = (rule: any, value: string, callback: Function) => {
  if (!value) {
    callback()
    return
  }
  
  // 支持的格式：YYYY-MM-DD, YYYY-MM, YYYY
  const datePattern = /^\d{4}-\d{2}-\d{2}$/
  const monthPattern = /^\d{4}-\d{2}$/
  const yearPattern = /^\d{4}$/
  
  if (!datePattern.test(value) && !monthPattern.test(value) && !yearPattern.test(value)) {
    callback(new Error('日期格式不正确，应为 YYYY-MM-DD、YYYY-MM 或 YYYY 格式'))
    return
  }
  
  // 验证日期有效性
  if (datePattern.test(value)) {
    const date = new Date(value)
    if (isNaN(date.getTime()) || date.toISOString().split('T')[0] !== value) {
      callback(new Error('日期无效'))
      return
    }
  }
  
  // 验证月份有效性
  if (monthPattern.test(value)) {
    const [year, month] = value.split('-').map(Number)
    if (month < 1 || month > 12) {
      callback(new Error('月份无效（应为 01-12）'))
      return
    }
    if (year < 1900 || year > 2100) {
      callback(new Error('年份超出有效范围（1900-2100）'))
      return
    }
  }
  
  // 验证年份有效性
  if (yearPattern.test(value)) {
    const year = parseInt(value)
    if (year < 1900 || year > 2100) {
      callback(new Error('年份超出有效范围（1900-2100）'))
      return
    }
  }
  
  callback()
}

// 检查两个日期格式是否一致
const validateDateFormatConsistency = (): boolean => {
  const base = baseDateValue.value
  const compare = compareDateValue.value
  
  if (!base || !compare) {
    return true // 如果有一个为空，不检查一致性
  }
  
  // 检查格式是否一致
  const datePattern = /^\d{4}-\d{2}-\d{2}$/
  const monthPattern = /^\d{4}-\d{2}$/
  const yearPattern = /^\d{4}$/
  
  const baseIsDate = datePattern.test(base)
  const baseIsMonth = monthPattern.test(base)
  const baseIsYear = yearPattern.test(base)
  
  const compareIsDate = datePattern.test(compare)
  const compareIsMonth = monthPattern.test(compare)
  const compareIsYear = yearPattern.test(compare)
  
  if (baseIsDate && !compareIsDate) {
    compareDateError.value = '对比日期格式不一致：应为日期格式（YYYY-MM-DD）'
    return false
  }
  if (baseIsMonth && !compareIsMonth) {
    compareDateError.value = '对比日期格式不一致：应为月份格式（YYYY-MM）'
    return false
  }
  if (baseIsYear && !compareIsYear) {
    compareDateError.value = '对比日期格式不一致：应为年份格式（YYYY）'
    return false
  }
  
  compareDateError.value = ''
  return true
}

const handleBaseDateInput = () => {
  baseDateError.value = ''
  validateDateFormat(null, baseDateValue.value || '', (error: Error | null) => {
    if (error) {
      baseDateError.value = error.message
    } else {
      baseDateError.value = ''
      localValue.time_comparison.base_date = baseDateValue.value
      validateDateFormatConsistency()
      emitParams()
    }
  })
}

const handleBaseDateBlur = () => {
  handleBaseDateInput()
  if (baseDateValue.value) {
    validateDateFormatConsistency()
  }
}

const handleCompareDateInput = () => {
  compareDateError.value = ''
  validateDateFormat(null, compareDateValue.value || '', (error: Error | null) => {
    if (error) {
      compareDateError.value = error.message
    } else {
      compareDateError.value = ''
      localValue.time_comparison.compare_date = compareDateValue.value
      validateDateFormatConsistency()
      emitParams()
    }
  })
}

const handleCompareDateBlur = () => {
  handleCompareDateInput()
  if (compareDateValue.value) {
    validateDateFormatConsistency()
  }
}

const handleBaseDateChange = (value: string | null) => {
  baseDateValue.value = value
  baseDateError.value = ''
  localValue.time_comparison.base_date = value
  if (value) {
    validateDateFormatConsistency()
  }
  emitParams()
}

const handleCompareDateChange = (value: string | null) => {
  compareDateValue.value = value
  compareDateError.value = ''
  localValue.time_comparison.compare_date = value
  if (value) {
    validateDateFormatConsistency()
  }
  emitParams()
}

// 显示日期选择器（暂时不实现，使用输入框）
const showDatePicker = (type: 'base' | 'compare') => {
  // 这里可以添加日期选择器的实现
  console.log(`显示${type === 'base' ? '基准' : '对比'}日期选择器`)
}

const getBaseDateText = (): string => {
  if (localValue.time_comparison.comparison_type === 'custom' && localValue.time_comparison.base_date) {
    return localValue.time_comparison.base_date
  }
  if (localValue.time_comparison.base_date) {
    return localValue.time_comparison.base_date
  }
  if (localValue.time_comparison.comparison_type === 'day') {
    const yesterday = new Date()
    yesterday.setDate(yesterday.getDate() - 1)
    return yesterday.toISOString().split('T')[0]
  }
  if (localValue.time_comparison.comparison_type === 'yesterday') {
    const dayBeforeYesterday = new Date()
    dayBeforeYesterday.setDate(dayBeforeYesterday.getDate() - 2)
    return dayBeforeYesterday.toISOString().split('T')[0]
  }
  if (localValue.time_comparison.comparison_type === 'month') {
    // 月份格式：YYYY-MM
    const now = new Date()
    const lastMonth = new Date(now.getFullYear(), now.getMonth(), 0)
    const year = lastMonth.getFullYear()
    const month = String(lastMonth.getMonth() + 1).padStart(2, '0')
    return `${year}-${month}`
  }
  if (localValue.time_comparison.comparison_type === 'year') {
    // 年份格式：YYYY
    const now = new Date()
    return String(now.getFullYear() - 1)
  }
  return '未设置'
}

const getCompareDateText = (): string => {
  if (localValue.time_comparison.comparison_type === 'custom' && localValue.time_comparison.compare_date) {
    return localValue.time_comparison.compare_date
  }
  if (localValue.time_comparison.compare_date) {
    return localValue.time_comparison.compare_date
  }
  if (localValue.time_comparison.comparison_type === 'day') {
    return new Date().toISOString().split('T')[0]
  }
  if (localValue.time_comparison.comparison_type === 'yesterday') {
    const yesterday = new Date()
    yesterday.setDate(yesterday.getDate() - 1)
    return yesterday.toISOString().split('T')[0]
  }
  if (localValue.time_comparison.comparison_type === 'month') {
    // 月份格式：YYYY-MM
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    return `${year}-${month}`
  }
  if (localValue.time_comparison.comparison_type === 'year') {
    // 年份格式：YYYY
    const now = new Date()
    return String(now.getFullYear())
  }
  return '未设置'
}

// 初始化日期
watch(() => localValue.time_comparison.comparison_type, () => {
  handleComparisonTypeChange()
}, { immediate: true })

watch(() => props.modelValue, (val) => {
  if (!val) return
  const next = JSON.parse(JSON.stringify(val))
  Object.assign(localValue, defaultValue(), next)
  sortDisplayFields()
  
  // 同步日期选择器
  if (next.time_comparison) {
    baseDateValue.value = next.time_comparison.base_date || null
    compareDateValue.value = next.time_comparison.compare_date || null
  }
}, { deep: true })

watch(() => props.templateMeta, (meta) => {
  if (meta?.defaultParams) {
    const next = JSON.parse(JSON.stringify(meta.defaultParams))
    Object.assign(localValue, defaultValue(), next)
    sortDisplayFields()
    handleComparisonTypeChange()
  }
}, { immediate: true })

const validate = () => {
  const errors: string[] = []
  if (!localValue.data_source_config.data_source_id) {
    errors.push('请选择数据源')
  }
  if (!localValue.platform_filter.selected_platforms?.length) {
    errors.push('至少选择一个平台')
  }
  if (localValue.time_comparison.comparison_type === 'custom') {
    if (!localValue.time_comparison.base_date) {
      errors.push('自定义模式下请选择基准日期')
    } else if (baseDateError.value) {
      errors.push(`基准日期格式错误：${baseDateError.value}`)
    }
    if (!localValue.time_comparison.compare_date) {
      errors.push('自定义模式下请选择对比日期')
    } else if (compareDateError.value) {
      errors.push(`对比日期格式错误：${compareDateError.value}`)
    }
    // 检查格式一致性
    if (localValue.time_comparison.base_date && localValue.time_comparison.compare_date) {
      if (!validateDateFormatConsistency()) {
        errors.push(compareDateError.value || '日期格式不一致')
      }
    }
  }
  emit('validate', { valid: errors.length === 0, errors })
  return errors.length === 0
}

defineExpose({ validate })
</script>
<style scoped>
.form-section {
  margin-bottom: 24px;
  padding: 24px;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.form-section:hover {
  border-color: #c0c4cc;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  transform: translateY(-1px);
}

.section-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #1f2937;
  font-size: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f0f0f0;
  position: relative;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 60px;
  height: 2px;
  background: linear-gradient(90deg, #409eff, #67c23a);
  border-radius: 1px;
}

.form-section:nth-child(1) .section-title::after {
  background: linear-gradient(90deg, #409eff, #67c23a);
}

.form-section:nth-child(2) .section-title::after {
  background: linear-gradient(90deg, #67c23a, #85ce61);
}

.form-section:nth-child(3) .section-title::after {
  background: linear-gradient(90deg, #e6a23c, #f7ba2a);
}

.form-section:nth-child(4) .section-title::after {
  background: linear-gradient(90deg, #f56c6c, #ff8b8b);
}

.section-title .el-icon {
  font-size: 18px;
  color: #409eff;
}

.data-source-icon {
  color: #409eff;
}

.platform-icon {
  color: #67c23a;
}

.time-comparison-icon {
  color: #e6a23c;
}

.display-fields-icon {
  color: #f56c6c;
}

.form-section :deep(.el-form-item) {
  margin-bottom: 20px;
}

.form-section :deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
  line-height: 32px;
}

.form-section :deep(.el-select) {
  width: 100%;
}

.form-section :deep(.el-select .el-input__inner) {
  border-radius: 8px;
  border: 1px solid #d1d5db;
  transition: all 0.3s ease;
}

.form-section :deep(.el-select .el-input__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.display-fields {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

/* 平台选择样式 */
.platform-selection-container {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background-color: #fafafa;
  margin-bottom: 16px;
}

.platform-checkbox-group {
  margin-bottom: 12px;
}

.platform-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
}

.platform-checkbox {
  margin: 0 !important;
}

.platform-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.platform-item:hover {
  background-color: rgba(64, 158, 255, 0.1);
}

.platform-icon {
  color: #409eff;
  font-size: 16px;
}

.platform-name {
  font-weight: 500;
  color: #303133;
}

.platform-code {
  font-size: 12px;
  color: #909399;
}

.quick-actions {
  display: flex;
  gap: 8px;
  padding-top: 12px;
  border-top: 1px solid #e4e7ed;
}

.help-icon {
  color: #909399;
  font-size: 14px;
  cursor: help;
}

.selected-preview {
  margin-top: 16px;
  padding: 12px;
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 8px;
}

.preview-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-weight: 500;
  color: #1e40af;
}

.preview-content {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.platform-tag {
  margin: 0 !important;
}

.summary-tag {
  margin: 0 !important;
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  border: none;
  color: #ffffff !important;
  font-weight: 600;
}

.summary-tag :deep(.el-icon) {
  color: #ffffff !important;
}

.platform-stats {
  margin-top: 12px;
}

/* 时间对比配置样式 */
.time-comparison-container {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background-color: #fafafa;
}

.comparison-type-section {
  margin-bottom: 20px;
}

.item-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-weight: 500;
  color: #303133;
}

.comparison-type-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.comparison-radio {
  flex: 1 1 calc(50% - 12px);
  margin: 0 !important;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: white;
  transition: all 0.3s ease;
}

.comparison-radio:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.comparison-radio.is-checked {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.custom-date-section {
  margin-bottom: 20px;
  padding: 16px;
  background-color: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.date-picker-row {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.date-input-item {
  flex: 1;
  margin-bottom: 0 !important;
}

.date-input-item :deep(.el-form-item__content) {
  display: flex;
  flex-direction: column;
  width: 100%;
  min-height: 74px; /* 输入框高度 + 错误提示区域高度 */
}

.error-message-wrapper {
  min-height: 32px;
  margin-top: 6px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.time-preview {
  padding: 12px;
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 8px;
}

.time-preview .preview-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-weight: 500;
  color: #1e40af;
}

.time-preview .preview-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.time-preview .preview-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.time-preview .label {
  color: #606266;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .platform-row {
    grid-template-columns: 1fr;
  }
  
  .quick-actions {
    flex-wrap: wrap;
  }
  
  .comparison-type-group {
    flex-direction: column;
  }
  
  .comparison-radio {
    flex: 1 1 100%;
  }
  
  .date-picker-row {
    flex-direction: column;
    gap: 12px;
  }
}

.comparison-radio :deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #409eff;
  border-color: #409eff;
}

.comparison-radio :deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #409eff;
}

.platform-checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #409eff;
  border-color: #409eff;
}

.platform-checkbox :deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #409eff;
}

.error-message {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #f56c6c;
  font-size: 12px;
  line-height: 1.5;
  padding: 4px 8px;
  background-color: #fef0f0;
  border-left: 3px solid #f56c6c;
  border-radius: 4px;
}

.error-icon {
  font-size: 14px;
  flex-shrink: 0;
}

.date-picker-row :deep(.el-input.is-error .el-input__wrapper) {
  box-shadow: 0 0 0 1px #f56c6c inset;
}

.date-picker-row :deep(.el-form-item.is-error .el-form-item__label) {
  color: #f56c6c;
}

.date-picker-row :deep(.el-input-group__append) {
  padding: 0;
}

.date-picker-row :deep(.el-input-group__append .el-button) {
  margin: 0;
  padding: 8px 12px;
}

.error-fade-enter-active {
  transition: all 0.3s ease-in;
}

.error-fade-leave-active {
  transition: all 0.2s ease-out;
}

.error-fade-enter-from {
  opacity: 0;
  transform: translateY(-4px);
}

.error-fade-leave-to {
  opacity: 0;
  transform: translateY(-4px);
}
</style>
